/**
 * 
 */
package elitech.vietnam.weatherfashion.tabs.self;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.backgroundtask.PostCommentTask;
import elitech.vietnam.weatherfashion.backgroundtask.PostLikeTask;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.ConfirmDialog;
import elitech.vietnam.weatherfashion.dialog.DialogUserInfo;
import elitech.vietnam.weatherfashion.dialog.EditPostDialog;
import elitech.vietnam.weatherfashion.dialog.PicPickerDialog;
import elitech.vietnam.weatherfashion.dialog.WarningDialog;
import elitech.vietnam.weatherfashion.dto.CommentDTO;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;
import elitech.vietnam.weatherfashion.tabs.BaseContainerFragment;
import elitech.vietnam.weatherfashion.tabs.zoompager.ZoomPagerItemFragment;
import elitech.vietnam.weatherfashion.widget.CommentAdapter;
import elitech.vietnam.weatherfashion.widget.LikeButton;
import elitech.vietnam.weatherfashion.widget.NotifyButton;

/**
 * @author Cong
 * 
 */
public class SelfPostFragment extends AbstractFragment implements View.OnClickListener {

	private static final int NUMTASK = 1;
	private PostDTO post;
	private ImageView image_useravatar, image_main;
	private TextView text_username, text_userstatus, text_commentcount, text_content, text_p_commentcount, mTextHeader;
	private LinearLayout layout_comments;
	private Button button_sendcomment, button_editpost, button_back, button_camera;
	private LikeButton button_like;
	private EditText textbox_comment;
	private NotifyButton button_notification;

	private CommentAdapter mCAdapter;
	private List<CommentDTO> comments;

	int postId = -1;
	int mTask = 0;
	
	public static SelfPostFragment init(PostDTO post) {
		SelfPostFragment frm = new SelfPostFragment();
		frm.post = post;
		return frm;
	}

	public static SelfPostFragment init(int postID) {
		SelfPostFragment frm = new SelfPostFragment();
		frm.postId = postID;
		frm.post = Utils.findPostSelf(postID);
		return frm;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.self_post, container, false);
		setupView(view);

		image_useravatar = (ImageView) view.findViewById(R.id.selfpost_image_useravatar);
		text_username = (TextView) view.findViewById(R.id.selfpost_textview_username);
		text_userstatus = (TextView) view.findViewById(R.id.selfpost_textview_userstatus);
		image_main = (ImageView) view.findViewById(R.id.selfpost_imageview_main);
		text_commentcount = (TextView) view.findViewById(R.id.selfpost_textview_commentcount);
		layout_comments = (LinearLayout) view.findViewById(R.id.selfpost_layout_comments);
		text_content = (TextView) view.findViewById(R.id.selfpost_textview_content);
		button_like = (LikeButton) view.findViewById(R.id.selfpost_button_like);
		button_sendcomment = (Button) view.findViewById(R.id.selfpost_button_sendcomment);
		textbox_comment = (EditText) view.findViewById(R.id.selfpost_textbox_comment);
		button_editpost = (Button) view.findViewById(R.id.selfpost_button_edit);
		text_p_commentcount = (TextView) view.findViewById(R.id.selfpost_profile_commentcount);
		mTextHeader = (TextView) view.findViewById(R.id.selfpost_text_header);
		button_back = (Button) view.findViewById(R.id.selfpost_button_back);
		button_camera = (Button) view.findViewById(R.id.selfpost_button_camera);
		button_notification = (NotifyButton) view.findViewById(R.id.button_notification);
		
		((MainActivity) getActivity()).setCurrentNotifyButton(button_notification);
		
		mTextHeader.setText(Html.fromHtml(getString(R.string.mystyle)));
		button_back.setOnClickListener(this);
		button_camera.setOnClickListener(this);

		MemberDTO m = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (m == null)
			button_notification.setVisibility(View.GONE);
		else 
			button_notification.setVisibility(View.VISIBLE);
		//button_notification.setOnClickListener(this);

		return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (!isAdded())
			return;
		onLoading(true);
		mTask = 0;
		
		button_like.setUp(true);
		
		if (this.post == null) {
			if (postId > 0)
				new SelfListPostLoadingTask().execute();
			else
				onNoData(true);
			return;
		}

		new GetCommentTask().execute();

		loadMember();
		loadPost();

		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(textbox_comment.getWindowToken(), 0);

	}

	@Override
	public void onResume() {
		super.onResume();
		
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(textbox_comment.getWindowToken(), 0);
		
		if (getActivity().getIntent().getIntExtra("POST_RELOAD", -1) > 0) {
			getActivity().getIntent().removeExtra("POST_RELOAD");
			getActivity().onBackPressed();
		}
	}

	public void loadMember() {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (user == null)
			return;
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// AppConfig.getInstance().appUser.getMemberPic(), image_useravatar);
		UrlImageViewHelper.setUrlDrawable(image_useravatar, Const.SERVER_IMAGE_URL + user.getMemberPic(), R.drawable.avatar);
		this.text_username.setText(user.getMemberName());
		this.text_userstatus.setText(user.getMemberProfile());

		button_editpost.setOnClickListener(this);
		image_useravatar.setOnClickListener(this);

	}

	public void loadPost() {
		text_content.setText(post.getContent());
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// this.post.getImage(), image_main);
		UrlImageViewHelper.setUrlDrawable(image_main, Const.SERVER_IMAGE_URL + this.post.getImage(), R.drawable.loading_time);
		button_like.setData(post.getLikes(), post.isLiked());
		image_main.setOnClickListener(this);
		button_like.setOnClickListener(this);
		button_sendcomment.setOnClickListener(this);
	}

	public void loadComments() {
		if (!isAdded())
			return;
		if (this.comments == null)
			this.comments = new ArrayList<CommentDTO>();
		mCAdapter = new CommentAdapter(getActivity(), R.layout.layout_comment, comments);
		mCAdapter.LoadList(layout_comments);
		this.text_commentcount.setText(this.comments.size() + getString(R.string._comments));
		this.text_p_commentcount.setText(String.valueOf(this.comments.size()));
		this.text_p_commentcount.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {

		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(textbox_comment.getWindowToken(), 0);
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (v.getId()) {
		case R.id.selfpost_button_like:
			button_like.setEnabled(false);
			if (user == null) {
				Utils.openLogin(getActivity());
			} else {
				String ms = getString(R.string.do_you_want_to_like_this_post_);
				if (post.isLiked())
					ms = getString(R.string.do_you_want_to_unlike_this_post_);
				new ConfirmDialog.Builder(getActivity())
				.setMessage(ms)
				.setYesClick(new ConfirmDialog.OnYesClick() {
					@Override
					public void doClick() {
						new PostLikeTask(getActivity(), button_like, post, !post.isLiked()).execute();
					}
				})
				.build()
				.show();
			}
			button_like.setEnabled(true);
			break;

		case R.id.selfpost_button_sendcomment:
			if (user == null) {
				Utils.openLogin(getActivity());
			} else if (!this.textbox_comment.getText().toString().trim().equals("")) {
				if (user.getId() != this.post.getStoreId())
					new PostCommentTask(getActivity(), this.post, mCAdapter, layout_comments, text_commentcount, text_p_commentcount).execute(this.textbox_comment.getText().toString(), "addNotification");
				else
					new PostCommentTask(getActivity(), this.post, mCAdapter, layout_comments, text_commentcount, text_p_commentcount).execute(this.textbox_comment.getText().toString());
				this.textbox_comment.setText("");
			}
			break;
		
		case R.id.selfpost_imageview_main:
			((BaseContainerFragment) getParentFragment()).replaceFragment(ZoomPagerItemFragment.init(Const.SERVER_IMAGE_URL + post.getImage()), true);
			break;

		case R.id.selfpost_button_edit:
			new EditPostDialog(getActivity(), post, user.getId()).show();
			break;

		case R.id.selfpost_image_useravatar:
			new DialogUserInfo(getActivity(), user).show();
			break;

		case R.id.selfpost_button_back:
			getActivity().onBackPressed();
			break;
			
		case R.id.selfpost_button_camera:
			if (user == null)
				Utils.openLogin(getActivity());
			else
				new PicPickerDialog(getActivity(), this).show();
			break;

		case R.id.button_notification:
			Log.w("Notification", "Num Count: " + WFApplication.getInstance().mListNoti.size());
			((MainActivity) getActivity()).mNotiWindow.showAsDropDown(button_notification);
			((MainActivity) getActivity()).mNotiWindow.notifyDataChanged();
			button_notification.setNumber(0);
			break;

		default:
			break;
		}
	}
	
	class GetCommentTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				comments = appService.getListComment(post.getId());
			} catch (IOException e) {
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			finishLoading();
			if (result != null) {
				new WarningDialog.Builder(getActivity())
				.setOnClick(new WarningDialog.OnButtonClick() {
					@Override
					public void doClick() {
						getActivity().onBackPressed();
					}
				}).createTimeOutDialog().show();
				return;
			}
			loadComments();
		}
	}
	
	class SelfListPostLoadingTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				Utils.getSelfData(getActivity());
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new WarningDialog.Builder(getActivity())
				.setOnClick(new WarningDialog.OnButtonClick() {
					@Override
					public void doClick() {
						getActivity().onBackPressed();
					}
				}).createTimeOutDialog().show();
				return;
			}
			post = Utils.findPostSelf(postId);
			if (post == null) {
				onNoData(true);
				return;
			}
			new GetCommentTask().execute();
			loadMember();
			loadPost();
		}
	}
	
	private void finishLoading() {
		mTask +=1;
		if (mTask == NUMTASK)
			onLoading(false);
	}

}
